package com.mobilepay.moneypig.model.activity.home;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.loonggg.rvbanner.lib.RecyclerViewBanner;
import com.mobilepay.moneypig.R;
import com.mobilepay.moneypig.base.BaseActivity;
import com.mobilepay.moneypig.config.Key;
import com.mobilepay.moneypig.config.NetConfig;
import com.mobilepay.moneypig.model.application.App;
import com.mobilepay.moneypig.okhttp.HttpUtils;
import com.mobilepay.moneypig.response.ResponseResult;
import com.mobilepay.moneypig.response.home.LoanData;
import com.mobilepay.moneypig.utils.CommonUtil;
import com.mobilepay.moneypig.utils.GsonUtil;
import com.mobilepay.moneypig.utils.acache.ACache;
import com.mobilepay.moneypig.view.WebViewActivity;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by xlm on 2017/8/2 0002
 */

public class ListApplyMoneyActivity extends BaseActivity {
    private static final String TAG = "ListApplyMoneyActivity";
    private RelativeLayout mRelativeBack;
    private RecyclerView mRecycleProduct;
    private RecyclerViewBanner mRecycleBanner;
    private List<LoanData.DataBean.LoanBean> creditBeen;
    private List<LoanData.DataBean.ListBean> listBeen;
    private CreditAdapter creditAdapter;
    private SmartRefreshLayout smartRefreshLayout;

    @Override
    protected void onSetContentView() {
        setContentView(R.layout.activity_listapply_money);
    }

    @Override
    protected void initViews() {
        mRelativeBack = (RelativeLayout) findViewById(R.id.money_back);
        mRecycleProduct = (RecyclerView) findViewById(R.id.credit_recycle);
        mRecycleBanner = (RecyclerViewBanner) findViewById(R.id.credit_banner);
        smartRefreshLayout = (SmartRefreshLayout) findViewById(R.id.credit_refresh);
    }

    @Override
    protected void afterOnCreate(Bundle savedInstanceState) {
        setRecyclebanner();
        setCreditAdapter();
        getData();
    }

    @Override
    protected void onSetListener() {
        mRelativeBack.setOnClickListener(this);
        creditAdapter.setProClickListener(new CreditAdapter.OnProductClick() {
            @Override
            public void click(int position, View view) {
                String url = listBeen.get(position).getUrl();
                if (!CommonUtil.isEmpty(url)) {
                    Intent intent = new Intent();
                    intent.setClass(getThis(), WebViewActivity.class);
                    intent.putExtra(Key.TITLE, listBeen.get(position).getTitle());
                    intent.putExtra(Key.URL, listBeen.get(position).getUrl());
                    startActivity(intent);
                }
            }
        });
        smartRefreshLayout.setEnableLoadmore(false);
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getData();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.money_back:
                finish();
                break;
        }
    }

    private void setRecyclebanner() {
        creditBeen = new ArrayList<>();
        mRecycleBanner.setRvBannerData(creditBeen);
        mRecycleBanner.setOnSwitchRvBannerListener(new RecyclerViewBanner.OnSwitchRvBannerListener() {
            @Override
            public void switchBanner(int i, AppCompatImageView appCompatImageView) {
                appCompatImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                Glide.with(appCompatImageView.getContext())
                        .load(creditBeen.get(i).getPath())
                        .into(appCompatImageView);
            }
        });
        mRecycleBanner.setOnRvBannerClickListener(new RecyclerViewBanner.OnRvBannerClickListener() {
            @Override
            public void onClick(int i) {
            }
        });
    }

    private void setCreditAdapter() {
        listBeen = new ArrayList<>();
        creditAdapter = new CreditAdapter(getThis());
        creditAdapter.setData(listBeen);
        mRecycleProduct.setLayoutManager(new LinearLayoutManager(getThis()));
        mRecycleProduct.setAdapter(creditAdapter);
    }

    private static class CreditAdapter extends RecyclerView.Adapter<CreditViewHolder> {

        private List<LoanData.DataBean.ListBean> list;
        private LayoutInflater inflater;
        private Context context;

        public CreditAdapter(Context context) {
            this.context = context;
            inflater = LayoutInflater.from(context);
        }

        public void setData(List<LoanData.DataBean.ListBean> listBeen) {
            this.list = listBeen;
        }

        @Override
        public CreditViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new CreditViewHolder(inflater.inflate(R.layout.item_product, parent, false));
        }

        @Override
        public void onBindViewHolder(CreditViewHolder holder, final int position) {
            LoanData.DataBean.ListBean listBean = list.get(position);
            if (listBean != null) {
                Glide.with(holder.itemView.getContext())
                        .load(listBean.getCover())
                        .placeholder(R.mipmap.icon)
                        .into(holder.mImageCorver);
                holder.mTextTitile.setText(listBean.getTitle());
                holder.mTextRate.setText(listBean.getAbstractX());
                holder.mTextIntroduce.setText(listBean.getMain());
                holder.mTextApply.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        onProductClick.click(position, v);
                    }
                });
            }
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        public void setProClickListener(OnProductClick productClick) {
            this.onProductClick = productClick;
        }

        private OnProductClick onProductClick;

        public interface OnProductClick {
            void click(int position, View view);
        }
    }

    private static class CreditViewHolder extends RecyclerView.ViewHolder {
        private ImageView mImageCorver;
        private TextView mTextTitile;
        private TextView mTextRate;
        private TextView mTextIntroduce;
        private TextView mTextApply;

        public CreditViewHolder(View itemView) {
            super(itemView);
            mImageCorver = (ImageView) itemView.findViewById(R.id.product_image);
            mTextTitile = (TextView) itemView.findViewById(R.id.product_name);
            mTextRate = (TextView) itemView.findViewById(R.id.product_rate);
            mTextIntroduce = (TextView) itemView.findViewById(R.id.product_introduce);
            mTextApply = (TextView) itemView.findViewById(R.id.product_btn);
        }
    }


    private void getData() {
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", NetConfig.getProduct);
        param.add("uid", String.valueOf(App.getApp().getUserInfo().getData().getUid()));
        param.add("scene_id", "3");
        param.add("image_name", "loan");
        param.add("sign", param.getMd5String());
        showProgress("加载中");
        HttpUtils.getInstance().params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                dismissProgress();
                smartRefreshLayout.finishRefresh();
                if (CommonUtil.isForeground(getThis())) {
                    showToastShort(getString(R.string.net_state));
                    String jsonString = ACache.get(App.getApp()).getAsString("loan");
                    if (!CommonUtil.isEmpty(jsonString)) {
                        setMoneyData(jsonString);
                    }
                }
            }

            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
                dismissProgress();
                smartRefreshLayout.finishRefresh();
                setMoneyData(string);
            }
        });
    }

    private void setMoneyData(String string) {
        if (HttpUtils.isJson(string)) {
            ResponseResult responseResult = GsonUtil.GsonToBean(string, ResponseResult.class);
            ACache.get(App.getApp()).put("loan", string);
            if (responseResult.getStatus() == 1) {
                LoanData productsData = GsonUtil.GsonToBean(string, LoanData.class);
                List<LoanData.DataBean.LoanBean> credit = productsData.getData().getLoan();
                List<LoanData.DataBean.ListBean> list = productsData.getData().getList();
                creditBeen.clear();
                listBeen.clear();
                creditBeen.addAll(credit);
                listBeen.addAll(list);
                creditAdapter.setData(listBeen);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mRecycleBanner.setRvBannerData(creditBeen);
                        creditAdapter.notifyDataSetChanged();
                    }
                });
                if (listBeen.size() != 0) {
                    setTxtMoneyShow(View.VISIBLE);
                } else
                    setTxtMoneyShow(View.GONE);
            } else {
                setTxtMoneyShow(View.GONE);
            }
        } else {
            setTxtMoneyShow(View.GONE);
        }
    }

    private void setTxtMoneyShow(final int visible) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                findViewById(R.id.txt_money).setVisibility(visible);
            }
        });
    }
}
